<template>
  <div class="app-container">
    <el-card>
      <!--      标题以及按钮-->
      <div slot="header" class="clearfix">
        <el-row
          justify="space-between"
          type="flex"
        >
          <el-col :span="8"><span style="font-size: 20px;">商品管理</span></el-col>
          <el-col :span="2">
            <el-button
              :loading="isLoading"
              icon="el-icon-circle-plus-outline"
              round
              type="success"
              @click="Add()"
            >添加
            </el-button>
          </el-col>
        </el-row>
      </div>
      <!--      标题以及按钮-->

      <!--      添加网站信息的子页面-->
      <el-dialog :visible.sync="dialogAddFormVisible" title="添加网站信息">
        <el-form ref="form" :model="form" :rules="rules">
          <el-form-item
            :label-width="formLabelWidth"
            label="商品名称"
            prop="ProductName"
          >
            <el-input
              v-model="form.productName"
              autocomplete="off"
              placeholder="请输入商品名称"
            />
          </el-form-item>
          <el-form-item
            :label-width="formLabelWidth"
            label="商品定价"
            prop="ProductPrice"
          >
            <el-input
              v-model.number="form.productPrice"
              autocomplete="off"
              placeholder="请输入商品定价"
            />
          </el-form-item>
          <el-form-item
            :label-width="formLabelWidth"
            label="商品库存"
            prop="ProductStock"
          >
            <el-input
              v-model.number="form.productStock"
              autocomplete="off"
              placeholder="请输入商品库存数量"
            />
          </el-form-item>
          <el-form-item
            :label-width="formLabelWidth"
            label="商品描述"
            prop="ProductDescription"
          >
            <el-input
              v-model="form.productDescription"
              autocomplete="off"
              placeholder="请对商品进行描述"
            />
          </el-form-item>
          <el-form-item
            :label-width="formLabelWidth"
            label="商品类别"
            prop="CategoryID"
          >
            <el-input
              v-model.number="form.categoryId"
              autocomplete="off"
              placeholder="请输入商品属于什么类别"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button icon="el-icon-circle-close" @click="handleAddCancel()">取 消</el-button>
          <el-button
            :loading="isLoading"
            icon="el-icon-circle-check"
            type="primary"
            @click="handleAdd()"
          >保 存
          </el-button>
        </div>
      </el-dialog>
      <!--      添加网站信息-->
      <el-table
        v-loading="listLoading"
        :data="list"
        border
        element-loading-text="Loading"
        fit
        highlight-current-row
      >
        <el-table-column align="center" label="产品编号">
          <template slot-scope="scope">
            {{ scope.row.productId }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="产品图片">
          <template slot-scope="scope">
            <img :src="scope.row.productImageUrl" alt="Product Image" style="width: 50px; height: 50px;">
          </template>
        </el-table-column>

        <el-table-column align="center" label="产品名">
          <template slot-scope="scope">
            {{ scope.row.productName }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="产品描述" width="200">
          <template slot-scope="scope">
            <span>{{ scope.row.productDescription }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="价格/元" width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.productPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="库存" width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.productStock }}</span>
          </template>
        </el-table-column>
        <el-table-column :formatter="formatDate()" align="center" label="创建时间">
          <template slot-scope="scope">
            <span>{{
              new Date(scope.row.creationDate).toLocaleString('zh', { hour12: false }).replaceAll('/', '-')
            }}</span>
          </template>
        </el-table-column>
        <el-table-column :formatter="formatDate" align="center" label="更新时间">
          <template slot-scope="scope">
            <span>{{
              new Date(scope.row.updateDate).toLocaleString('zh', { hour12: false }).replaceAll('/', '-')
            }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="产品类别">
          <template slot-scope="scope">
            <span>{{ scope.row.categoryId }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              v-show="!scope.row.isEdit"
              circle
              icon="el-icon-edit"
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
            />
            <el-button
              v-show="!scope.row.isEdit"
              circle
              icon="el-icon-delete"
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>

      <el-dialog :visible.sync="dialogFormVisible" title="编辑网站信息">
        <el-form ref="form" :model="form" :rules="rules" enctype="multipart/form-data">
          <!--图片更改部分-->
          <!--文件上传-->
          <el-upload
            ref="uploadImage"
            action=""
            class="avatar-uploader"
            :show-file-list="false"
            :http-request="uploadImg"
            :multiple="false"
            :auto-upload="false"
            :on-change="imgSaveToUrl"
            :before-upload="beforeAvatarUpload"
            accept="image/png,image/jpg,image/jpeg"
          >
            <img
              v-if="dataForm.headUrl"
              :src="dataForm.headUrl"
              class="avatar"
              alt="无"
            >
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            />
          </el-upload>
          <!---->
          <!--图片更改部分-->
          <el-form-item
            :label-width="formLabelWidth"
            label="商品名称"
            prop="ProductName"
          >
            <el-input
              v-model="form.productName"
              autocomplete="off"
              placeholder="请输入商品名称"
            />
          </el-form-item>
          <el-form-item
            :label-width="formLabelWidth"
            label="商品定价"
            prop="ProductPrice"
          >
            <el-input
              v-model.number="form.productPrice"
              autocomplete="off"
              placeholder="请输入商品定价"
            />
          </el-form-item>
          <el-form-item
            :label-width="formLabelWidth"
            label="商品库存"
            prop="ProductStock"
          >
            <el-input
              v-model.number="form.productStock"
              autocomplete="off"
              placeholder="请输入商品库存数量"
            />
          </el-form-item>
          <el-form-item
            :label-width="formLabelWidth"
            label="商品描述"
            prop="ProductDescription"
          >
            <el-input
              v-model="form.productDescription"
              autocomplete="off"
              placeholder="请对商品进行描述"
            />
          </el-form-item>
          <el-form-item
            :label-width="formLabelWidth"
            label="商品类别"
            prop="CategoryID"
          >
            <el-input
              v-model.number="form.categoryId"
              autocomplete="off"
              placeholder="请输入商品属于什么类别"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button icon="el-icon-circle-close" @click="handleCancel()">取 消</el-button>
          <el-button
            :loading="isLoading"
            icon="el-icon-circle-check"
            type="primary"
            @click="handleSave()"
          >保 存
          </el-button>
        </div>
      </el-dialog>

      <!--分页工具条-->
      <el-pagination
        :background="background"
        :current-page="currentPage"
        :page-size="10"
        :page-sizes="[5, 10, 15, 20]"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script>

import { formatDate } from 'element-ui'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      background: true,
      // 每页显示的条数
      pageSize: 10,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      list: null,
      listLoading: true,
      // siteList: [],
      dialogFormVisible: false,
      dialogAddFormVisible: false,
      isLoading: false,
      formLabelWidth: '120px',
      form: {
        // 产品的form
        ProductName: '',
        ProductPrice: '',
        ProductStock: '',
        ProductDescription: '',
        ProductImageURL: '',
        UpdateDate: new Date(),
        CategoryID: 0,
        sellerId: 0
      },
      // 文件上传的参数
      dialogImageUrl: '',
      dialogVisible: false,
      pictureFile: '',
      dataForm: { headUrl: '' },
      img: null,
      imgChanged: false,
      // 表单数据校验规则
      rules: {
        productName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 3, message: '长度不得小于 3 个字符', trigger: 'blur' }
        ],
        productPrice: [
          { required: true, message: '请输入商品库存量', trigger: 'blur' }
        ],
        productStock: [
          { required: true, message: '请输入商品库存量', trigger: 'blur' }
        ],
        productDescription: [
          { required: true, message: '请输入商品描述', trigger: 'blur' }
        ],
        categoryID: [
          { required: true, message: '请输入商品类别', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getProduct()
  },
  methods: {
    formatDate() {
      return formatDate
    },
    // 查询分页数据
    getProduct() {
      this.$store
        .dispatch('product/getList', {
          Page: this.currentPage,
          ageSize: this.pageSize
        })
        .then((res) => {
          if (res.code === 0) {
            const { data } = res
            this.list = data.rows
            this.form.sellerId = data.rows[0].userId
            this.listLoading = false
            this.totalCount = data.total
          } else {
            this.$message.error(res.msg)
          }
        })
    },
    // 分页控件函数--start
    handleSizeChange(val) {
      this.pageSize = val
      this.getProduct()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getProduct()
    },
    // 分页控件函数--end
    Add() {
      this.dialogAddFormVisible = true
    },
    handleAdd() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.isLoading = true
          this.$store.dispatch('product/addList', this.form).then((res) => {
            console.log(res)
            if (res.code === 0) {
              this.dialogAddFormVisible = false
              this.$message.success(res.msg)
              this.form = {}
              this.getProduct()
            } else {
              this.$message.error(res.msg)
            }
          })
          this.isLoading = false
        } else {
          return false
        }
      })
    },
    handleAddCancel() {
      this.dialogAddFormVisible = false
      this.form = {}
      this.$message.info('取消添加')
    },
    handleEdit(index, row) {
      this.form = row
      this.dialogFormVisible = true
    },
    handleCancel() {
      this.dialogFormVisible = false
      this.getProduct()
      this.form = {}
      this.$message.info('取消编辑')
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png' || 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG,PNG,JPEG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    imgSaveToUrl(event) {
      if (this.beforeAvatarUpload(event)) {
        var URL = null
        if (window.createObjectURL !== undefined) {
          // basic
          URL = window.createObjectURL(event.raw)
        } else if (window.URL !== undefined) {
          // mozilla(firefox)
          URL = window.URL.createObjectURL(event.raw)
        } else if (window.webkitURL !== undefined) {
          // webkit or chrome
          URL = window.webkitURL.createObjectURL(event.raw)
        }
        this.dataForm.headUrl = URL
        this.imgChanged = true
      }
    },
    // 自定义上传方法，使用上传组件的submit()后才会触发以获取文件实体
    uploadImg(param) {
      this.img = param.file
    },
    // 上传文件
    async uploadFile() {
      try {
        if (this.imgChanged) {
          // 触发上传
          this.$refs.uploadImage.submit()
          // 创建 FormData
          const formData = new FormData()
          // 如果有图片，添加到 FormData 中
          if (this.img) {
            formData.append('file', this.img)
          }
          const res = await this.$store.dispatch('product/uploadFile', formData)
          if (res.code === 0) {
            this.form.productImageUrl = res.data
            this.listLoading = false
          } else {
            this.$message.error(res.msg)
          }
        }
      } catch (error) {
        // 处理上传文件时的错误
        console.error('Error during file upload:', error)
        throw error // 将错误传播出去，以便在 uploadAndSubmit 中捕获
      }
    },

    async handleSave() {
      try {
        await this.uploadFile()
        await this.$refs['form'].validate((valid) => {
          this.form.UpdateDate = new Date() // 使用浏览器默认的本地化格式
          if (valid) {
            this.isLoading = true
            this.$store.dispatch('product/UpdateList', this.form).then((res) => {
              if (res.code === 0) {
                this.dialogFormVisible = false
                this.form = {}
                this.$message.success(res.msg)
                this.isLoading = false
              } else {
                this.$message.error(res.msg)
              }
              this.isLoading = false
            })
          } else {
            return false
          }
        })
      } catch (error) {
        // 处理上传文件时的错误
        console.error('文件上传错误:', error)
        throw error // 将错误传播出去，以便在 uploadAndSubmit 中捕获
      }
    },
    handleDelete(index, row) {
      console.log(row)
      this.$confirm(
        '此操作将删除商品：' +
        row.productName +
        ' 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$store.dispatch('product/DeleteList', row).then((res) => {
            if (res.code === 0) {
              this.$message.success(res.msg)
              this.dialogFormVisible = false
              this.getProduct()
            } else {
              this.$message.error(res.msg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}

function time(time = +new Date()) {
  var date = new Date(time + 8 * 3600 * 1000)
  return date.toJSON().substr(0, 19).replace('T', ' ').replace(/-/g, '.')
}

time() // "2018.08.09 18:25:54"
</script>

<style>
.el-table {
  font-size: 13px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
